package cn.xzqwjw.taskmanager.controller.api_public;

import cn.xzqwjw.taskmanager.service.UlFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.util.Objects;

/**
 * 提供一些公用的、不需要进行jwt验证的接口地址-下载相关
 *
 * @author rush
 */
@RestController
@RequestMapping("/api-public/file")
public class PublicUlFileController {

  private final UlFileService ulFileService;

  @Autowired
  public PublicUlFileController(UlFileService ulFileService) {
    this.ulFileService = ulFileService;
  }

  // ==================== 下载文件 ====================

  @GetMapping("/download/stream/{uuid}")
  public void downloadAsStream(
      @NotBlank(message = "文件uuid不能为空")
      @PathVariable String uuid) {
    ServletRequestAttributes requestAttributes =
        (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    if (Objects.isNull(requestAttributes)) {
      return;
    }
    HttpServletResponse response = requestAttributes.getResponse();
    if (Objects.isNull(response)) {
      return;
    }
    ulFileService.downloadAsStream(response, uuid);
  }

  @GetMapping("/download/entity/{uuid}")
  public ResponseEntity<InputStreamResource> downloadAsResponseEntity(
      @NotBlank(message = "文件uuid不能为空")
      @PathVariable String uuid) {
    return ulFileService.downloadAsResponseEntity(uuid);
  }

  // ==================== 显示图像文件 ====================

  @GetMapping(
      value = "/image/{uuid}",
      produces = {
          MediaType.IMAGE_JPEG_VALUE,
          MediaType.IMAGE_GIF_VALUE,
          MediaType.IMAGE_PNG_VALUE
      }
  )
  public byte[] showImgAsStream(
      HttpServletResponse response,
      @RequestParam(value = "FlagThumb", defaultValue = "false") Boolean flagThumb,
      @NotBlank(message = "文件uuid不能为空")
      @PathVariable String uuid) {
    return ulFileService.showImgAsStream(response, uuid, flagThumb);
  }

}
